package me.ljd.yigo.mid.function;

import com.bokesoft.yigo.mid.base.DefaultContext;
import com.bokesoft.yigo.mid.parser.BaseMidFunctionImpl;
import com.bokesoft.yigo.parser.BaseFunImplCluster;
import com.bokesoft.yigo.parser.IExecutor;
import com.bokesoft.yigo.struct.datatable.DataTable;
import com.bokesoft.yigo.struct.document.Document;
import com.bokesoft.yigo.struct.exception.StructException;

public class MidReDevExt extends BaseFunImplCluster {
	class AutoGenSQLFunction extends BaseMidFunctionImpl{

		@Override
		public Object evalImpl(String name, DefaultContext context, Object[] args, IExecutor executor)
				throws Throwable {
			Document document = context.getDocument();
			try {
				DataTable head = document.get("TableLinkHead");
				StringBuffer sql = new StringBuffer("select ");
				DataTable dtCol = document.get("TableColumns");
				//dtCol.beforeFirst();
				int index = 0;
				while(dtCol.next()) {
					if(dtCol.getInt("Is_Select")==1) {
						index ++;
						if(index>1) {sql.append(",");}
						sql.append(dtCol.getString("Column_Name")).append(" C"+index);
					}
				}
				sql.append(" from ").append(head.getString("NO"));
				sql.append(" where 1=1 ");
				dtCol.beforeFirst();
				while(dtCol.next()) {
					if(dtCol.getInt("Is_Where")==1) {
						Object defaultValue = dtCol.getObject("ColumnDefaultValue");
						sql.append(" AND ").append(dtCol.getString("Column_Name")).append("=").append("'"+defaultValue+"'");
					}
				}
				head.setString("SQL", sql.toString());
			} catch (StructException e) {
				System.out.println("AutoGenSQLFunction出错");
				e.printStackTrace();
			}
			return true;
		}
		
	}

	@Override
	public Object[][] getImplTable() {
		return new Object[][]{
			{"AutoGenSQL", new AutoGenSQLFunction()}
		};
	}

}
